package com.yqw.onlineDocs.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yqw.onlineDocs.annotation.AuthCheck;
import com.yqw.onlineDocs.annotation.DocumentPermissionCheck;
import com.yqw.onlineDocs.common.BaseResponse;
import com.yqw.onlineDocs.common.DeleteRequest;
import com.yqw.onlineDocs.common.ErrorCode;
import com.yqw.onlineDocs.common.ResultUtils;
import com.yqw.onlineDocs.constant.DocumentPermissionConstant;
import com.yqw.onlineDocs.constant.UserConstant;
import com.yqw.onlineDocs.exception.BusinessException;
import com.yqw.onlineDocs.exception.ThrowUtils;
import com.yqw.onlineDocs.model.dto.documentVersion.*;
import com.yqw.onlineDocs.model.entity.Document;
import com.yqw.onlineDocs.model.entity.DocumentVersion;
import com.yqw.onlineDocs.model.entity.User;
import com.yqw.onlineDocs.model.vo.DocumentVersionVO;
import com.yqw.onlineDocs.service.DocumentService;
import com.yqw.onlineDocs.service.DocumentVersionService;
import com.yqw.onlineDocs.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 文档版本历史接口
 */
@RestController
@RequestMapping("/documentVersion")
@Slf4j
public class DocumentVersionController {

    @Resource
    private DocumentVersionService documentVersionService;

    @Resource
    private DocumentService documentService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建文档版本历史
     *
     * @param documentVersionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addDocumentVersion(@RequestBody DocumentVersionAddRequest documentVersionAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(documentVersionAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        DocumentVersion documentVersion = new DocumentVersion();
        BeanUtils.copyProperties(documentVersionAddRequest, documentVersion);
        // 数据校验
        documentVersionService.validDocumentVersion(documentVersion, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        documentVersion.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = documentVersionService.save(documentVersion);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newDocumentVersionId = documentVersion.getId();
        return ResultUtils.success(newDocumentVersionId);
    }

    /**
     * 删除文档版本历史
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @DocumentPermissionCheck(permission = DocumentPermissionConstant.DOCUMENT_WRITE, documentIdParam = "id")
    public BaseResponse<Boolean> deleteDocumentVersion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        DocumentVersion oldDocumentVersion = documentVersionService.getById(id);
        ThrowUtils.throwIf(oldDocumentVersion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldDocumentVersion.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = documentVersionService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新文档版本历史（仅管理员可用）
     *
     * @param documentVersionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateDocumentVersion(@RequestBody DocumentVersionUpdateRequest documentVersionUpdateRequest) {
        if (documentVersionUpdateRequest == null || documentVersionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        DocumentVersion documentVersion = new DocumentVersion();
        BeanUtils.copyProperties(documentVersionUpdateRequest, documentVersion);
        // 数据校验
        documentVersionService.validDocumentVersion(documentVersion, false);
        // 判断是否存在
        long id = documentVersionUpdateRequest.getId();
        DocumentVersion oldDocumentVersion = documentVersionService.getById(id);
        ThrowUtils.throwIf(oldDocumentVersion == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = documentVersionService.updateById(documentVersion);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取文档版本历史（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<DocumentVersionVO> getDocumentVersionVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        DocumentVersion documentVersion = documentVersionService.getById(id);
        ThrowUtils.throwIf(documentVersion == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(documentVersionService.getDocumentVersionVO(documentVersion, request));
    }

    /**
     * 分页获取文档版本历史列表（仅管理员可用）
     *
     * @param documentVersionQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<DocumentVersion>> listDocumentVersionByPage(@RequestBody DocumentVersionQueryRequest documentVersionQueryRequest) {
        long current = documentVersionQueryRequest.getCurrent();
        long size = documentVersionQueryRequest.getPageSize();
        // 查询数据库
        Page<DocumentVersion> documentVersionPage = documentVersionService.page(new Page<>(current, size),
                documentVersionService.getQueryWrapper(documentVersionQueryRequest));
        return ResultUtils.success(documentVersionPage);
    }

    /**
     * 分页获取文档版本历史列表（封装类）
     *
     * @param documentVersionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<DocumentVersionVO>> listDocumentVersionVOByPage(@RequestBody DocumentVersionQueryRequest documentVersionQueryRequest,
                                                                             HttpServletRequest request) {
        long current = documentVersionQueryRequest.getCurrent();
        long size = documentVersionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<DocumentVersion> documentVersionPage = documentVersionService.page(new Page<>(current, size),
                documentVersionService.getQueryWrapper(documentVersionQueryRequest));
        // 获取封装类
        return ResultUtils.success(documentVersionService.getDocumentVersionVOPage(documentVersionPage, request));
    }

    /**
     * 分页获取当前登录用户创建的文档版本历史列表
     *
     * @param documentVersionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<DocumentVersionVO>> listMyDocumentVersionVOByPage(@RequestBody DocumentVersionQueryRequest documentVersionQueryRequest,
                                                                               HttpServletRequest request) {
        ThrowUtils.throwIf(documentVersionQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        documentVersionQueryRequest.setUserId(loginUser.getId());
        long current = documentVersionQueryRequest.getCurrent();
        long size = documentVersionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<DocumentVersion> documentVersionPage = documentVersionService.page(new Page<>(current, size),
                documentVersionService.getQueryWrapper(documentVersionQueryRequest));
        // 获取封装类
        return ResultUtils.success(documentVersionService.getDocumentVersionVOPage(documentVersionPage, request));
    }

    /**
     * 编辑文档版本历史（给用户使用）
     *
     * @param documentVersionEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editDocumentVersion(@RequestBody DocumentVersionEditRequest documentVersionEditRequest, HttpServletRequest request) {
        if (documentVersionEditRequest == null || documentVersionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        DocumentVersion documentVersion = new DocumentVersion();
        BeanUtils.copyProperties(documentVersionEditRequest, documentVersion);
        // 数据校验
        documentVersionService.validDocumentVersion(documentVersion, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = documentVersionEditRequest.getId();
        DocumentVersion oldDocumentVersion = documentVersionService.getById(id);
        ThrowUtils.throwIf(oldDocumentVersion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldDocumentVersion.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = documentVersionService.updateById(documentVersion);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 回退文档版本历史（给用户使用）
     *
     * @param documentVersionBacktrackRequest
     * @param request
     * @return
     */
    @PostMapping("/backtrack")
    @DocumentPermissionCheck(permission = DocumentPermissionConstant.DOCUMENT_WRITE)
    public BaseResponse<Boolean> backtrackDocumentVersion(@RequestBody DocumentVersionBacktrackRequest documentVersionBacktrackRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(documentVersionBacktrackRequest == null, ErrorCode.PARAMS_ERROR, "参数错误");
        Long id = documentVersionBacktrackRequest.getId();
        Long documentId = documentVersionBacktrackRequest.getDocumentId();
        // 判断是否存在
        DocumentVersion oldDocumentVersion = documentVersionService.getById(id);
        ThrowUtils.throwIf(oldDocumentVersion == null, ErrorCode.NOT_FOUND_ERROR, "文档版本不存在");
        Document document = documentService.getById(documentId);
        ThrowUtils.throwIf(document == null, ErrorCode.NOT_FOUND_ERROR, "文档不存在");
        // 操作数据库
        // document参数补充
        document.setTitle(oldDocumentVersion.getTitle());
        document.setContent(oldDocumentVersion.getContent());
        boolean result = documentService.updateById(document);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }
    // endregion
}
